package com.raycloud.robot.kmkf.open.template.utils;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: 刘东（挂兰）
 * @Date: 2023/05/29/下午5:34
 * @Description:
 */
public class DateUtils {

    private static DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");


    /**
     * 获取多少天前的Date
     *
     * @param localDateTime 时间
     * @return
     */
    public static Date toBeforeDate(LocalDateTime localDateTime, Integer beforeDay) {
        if (Objects.nonNull(beforeDay) && beforeDay > 0) {
            localDateTime = localDateTime.minusDays(beforeDay);
        }
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDate stringToLocalDate(String date) {
        return LocalDate.parse(date, fmt);
    }

    /* Date转为LocalDateTime */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        if (null == date) {
            return null;
        }
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }
    public static String longToString(Long time) {
        if (Objects.isNull(time)) {
            return null;
        }
        return localDateTimeToString(longToLocalDateTime(time));
    }

    public static LocalDateTime longToLocalDateTime(Long time) {
        if (null == time) {
            return null;
        }
        Instant instant = Instant.ofEpochMilli(time);
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }

    public static String localDateTimeToString(LocalDateTime localDateTime) {
        if (null == localDateTime) {
            return null;
        }
        return localDateTime.format(formatDate);
    }


}
